﻿@model Xms.Web.Models.PrivilegeResourceModel

<div class="container-fluid">
    <div class="row">
        <div class="col-sm-4">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title">
                        <a data-toggle="collapse"
                           href="#collapseOne">
                            <strong id="name">@app.T[Model.ResourceName].IfEmpty(Model.ResourceName)</strong> - <strong>权限控制启用状态</strong>
                        </a>
                    </h3>
                </div>
                <div id="collapseOne" class="panel-collapse collapse in">
                    <div class="panel-body">
                        <form id="editform" class="form-horizontal text-center" data-jsonajax="true" data-istip="true" action="/@(app.OrganizationUniqueName)@Model.ResourceOwnerDescriptor.PrivilegeStateEndpoint" method="post">
                            @Html.AntiForgeryToken()
                            @Html.HiddenFor(x => x.ResourceName)
                            <div class="btn-group">
                                <button class="btn btn-default" type="button" data-toggle="button" id="toggleChecked" data-state="1">
                                    <span class="glyphicon glyphicon-check"></span> @app.T["check_all"] / <span class="glyphicon glyphicon-unchecked"></span> @app.T["cancel"]
                                </button>
                                <button class="btn btn-primary" type="submit"><span class="glyphicon glyphicon-saved"></span> @app.T["save"]</button>
                            </div>
                            <hr />
                            <div class="">
                                <div class="input-group"><input class="form-control" id="tree_searcher" /><span class="input-group-addon"><em class="glyphicon glyphicon-search"></em></span></div>
                            </div>
                            <div id="tree1" class="text-left" data-url="@("/"+app.OrganizationUniqueName)@Model.ResourceOwnerDescriptor.ResourceEndpoint" style="min-height:400px;max-height:400px; overflow:auto; padding:0 5px;">
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-sm-8">
            <table class="table table-hover table-bordered  table-striped table-condensed">
                <thead>
                    <tr>
                        <th>@app.T["name"]</th>
                        <th width="30%">@app.T["operation"]</th>
                    </tr>
                </thead>
                <tbody data-bind="foreach: lines">
                    <tr>
                        <td>
                            <a href="#" data-bind="click: $root.click"><span data-bind="text: modulelocalizedname"></span></a>
                        </td>
                        <td>
                            <a class="btn btn-info btn-xs" data-bind="click: $root.click"><span class="glyphicon glyphicon-cog"></span></a>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>
@section Header {
    <link href="/content/css/jqtree.css?v=@app.PlatformSettings.VersionNumber" rel="stylesheet">
}
@section Scripts {
    <script src="/content/js/xms.utility.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/jquery.form.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/jquery-validate/jquery.validate.min.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/xms.web.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/xms.jquery.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/tree.jquery.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/knockout-2.2.0.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script>
        var $tree = $('#tree1'), $editform = $("#editform"), resourceEndpoint = '@("/"+app.OrganizationUniqueName)@Model.ResourceOwnerDescriptor.ResourceEndpoint';
        $(function () {
            Xms.Web.Form($editform, function (response) {
                $('input[value^="parentid_"]').prop('disabled', false);
              //  Xms.Web.Toast(response.Content,response.IsSuccess);
            }, null, function () {
                    $('input[value^="parentid_"]').prop('disabled', true)
            });
            $("#toggleChecked").click(function () {
                var state = $(this).attr("data-state");
                if (state == 1) {
                    $tree.find("input[type=checkbox]").prop("checked", true);
                    $(this).attr("data-state", 0).removeClass("active");
                } else {
                    $tree.find("input[type=checkbox]").prop("checked", false);
                    $(this).attr("data-state", 1).addClass("active");
                }
            });
            function searchTreeData(e) {
                 var $tree_searcher = $('#tree_searcher'),
                    val = $tree_searcher.val();
                var $tree1 = $('#tree1');
                $tree1.find('>ul>li.jqtree_common').hide();
                $tree1.find('>ul>li.jqtree_common').find('.jqtree-toggler-left').text('►');
                if (val != '') {
                    $tree1.find('.jqtree-title').each(function () {
                        var name = $(this).text();
                        var $li = $(this).parents('li:first');
                        if (name != '' && name.indexOf(val) != -1) {
                          //  $li.show();
                            //if ($li.parents('li:first').is(':hidden')) {
                            $li.parents('li').show().find('.jqtree-toggler-left').text('▼');
                                $li.parents('li').children('ul').show();
                          //  }
                           // $li.parents('li:first')
                        } else {
                           // $li.parents('li:first').find('.jqtree-toggler-left').addClass('jqtree-closed');
                          //  $li.parents('li').show().find('.jqtree-toggler-left').text('►');
                           //  $li.parents('li').hide()
                          //  $li.hide();
                        }
                    });

                } else {
                    $tree1.find('li.jqtree_common').show();
                }

            }
            var debound = $.deboundsEvent(100);
            $('#tree_searcher').on('change', function (e) {
                var self = this;
                //if (e.keyCode == '13') {
                debound(function () {
                    searchTreeData.call(self, e)
                    })
               // }
            }).next().on('click', function (e) {
               var self = this;
                debound(function () {
                    searchTreeData.call(self, e)
                    })
            })

            var treeDatas = [];
            $tree.tree({
                autoOpen: false
                , onTreeFinished: function (data, parent_node) {
                    console.log(data, parent_node);
                    var folder = $tree.find('.jqtree-folder');
                    folder.each(function () {
                        var $that = $(this);
                        var list = $that.children('ul');
                        var checkboxs = list.find('input[type="checkbox"]');
                        var checkeds = list.find('input[type="checkbox"]:checked');
                        if (checkboxs.length == checkeds.length) {
                            $that.children('.jqtree-element').find('input[type="checkbox"]').prop('checked', true);
                            $that.children('.jqtree-element').find('a').trigger('click');
                        }
                    });
                }
                , onCreateLi: function (node, $li) {
                    $li.show();
                    var isdisabled = '';
                    if (node.id && node.id.indexOf('parentid') != -1) {
                        isdisabled = 'disabled';
                    }
                    if (treeDatas.length != 1) {
                        $li.find('.jqtree-title').before('<input type="checkbox" name="objectid" onclick="setState(this)"  value="' + node.id+ '" ' + (node.authorizationenabled ? 'checked' : '') + ' />&nbsp;&nbsp;');
                    } else if (treeDatas.length == 1 && node.children && node.children.length==0) {
                         $li.find('.jqtree-title').before('<span style="margin-left:10px;" /><input type="checkbox" '+isdisabled+' name="objectid" onclick="setState(this)" value="' + node.id + '" '+(node.authorizationenabled ? 'checked':'')+' />&nbsp;&nbsp;');
                    }

                }
                , selectable: false,
                onCanSelectNode: function (node) {
                    $tree.tree('openNode', node);
                    return true;
                }
                , dataFilter: function (data) {
                    //var ResourceName = $("#ResourceName").val();
                    //loadPrivilegeResources(ResourceName);
                    var datas = Xms.Web.GetAjaxResult(data).content;
                    console.log(datas)
                    treeDatas = datas;
                    handlerDatas(datas);
                    return datas;
                }
            });
            var count = 0;
            function handlerDatas(datas) {

                $.each(datas, function (i, n) {
                    if (!n.id) {
                        n.id = 'parentid_' + Xms.Utility.Guid.NewGuid().ToString()
                    }
                    if (n.children && n.children.length > 0) {
                        $.each(n.children, function (ii, nn) {
                            nn._parentid = n.id;
                        });
                        handlerDatas(n.children);
                    }
                    //if (!n.children && count<1) {
                    //    n.children = [{id:'234234234',label:'fdsfdsf'}];
                    //    count++;
                    //}
                });
            }
            Xms.Web.GetJson(ORG_SERVERURL + "/api/security/ResourceOwners", null, function (data) {
                if (!data) return;
                console.log('data=', data);
                data = Xms.Web.GetAjaxResult(data);
                var result = data.content;
                var Items = function () {
                    var self = this;
                    result = $.grep(result, function (n, i) {
                        n.modulelocalizedname = n.modulelocalizedname || '';
                        return n.statecode == 1;
                    });
                    self.lines = ko.observableArray(result);

                    self.click = function (item) {
                        $("#ResourceName").val(item.modulename);
                        $("#name").text(item.modulelocalizedname);
                        $tree.data('url', ORG_SERVERURL + item.resourceendpoint);
                        $tree.tree('reload');
                        loadPrivilegeResources(item.modulename);
                    }
                }
                var _item = new Items();
                console.log(_item);
                ko.applyBindings(_item);
            });
        });

        function loadPrivilegeResources(resourcename) {
            resourcename = resourcename || $("#ResourceName").val();

            Xms.Web.GetJson(resourceEndpoint+'?authorizationEnabled=true', null, function (data) {
                if (!data.IsSuccess) return;
                var result = data.content;
                console.info(result);

                if (result.length > 0) {
                    $(result).each(function (i, n) {
                        if (!n.id) {
                            var treeid = Xms.Utility.Guid.EmptyGuid.ToString()
                            n.id = treeid;
                            n.isparent = true;
                        }
                        setLoadedChildrenSelected(n.objectid);
                    });
                }
                else {
                    var node = $tree.tree('getNodeById', Xms.Utility.Guid.EmptyGuid.ToString());
                    if (node) {
                        $tree.tree('openNode', node);
                    }
                }
            });
        }
        function setChildrenSelected(nodeid) {
            var node = $tree.tree('getNodeById', nodeid);
            if (!node) return;
            $(node.element).find("input[type=checkbox][value=" + nodeid + "]").prop("checked", true);
            if (node) {
                $tree.tree('openNode', node);
            }
            for (var i = 0; i < node.children.length; i++) {
                var child = node.children[i];
                if (child.children.length > 0) {
                    setChildrenSelected(child.id);
                }

                var childnode = $tree.tree('getNodeById', child.id);
                $(childnode.element).find("input[type=checkbox][value=" + child.id + "]").prop("checked", true);
                if (childnode) {
                    $tree.tree('openNode', childnode);
                }

            }
        }
        function setLoadedChildrenSelected(nodeid) {
            var node = $tree.tree('getNodeById', nodeid);
            if (!node) return;
            $(node.element).find("input[type=checkbox][value=" + nodeid + "]").prop("checked", true);
            if (node) {
                $tree.tree('openNode', node);
            }
            if (node.children.length == 0) {
                var par_ele = $(node.element).parent().siblings(".jqtree-element");
                if (par_ele.length > 0) {
                    var paridDom = par_ele.find("input[name='objectid']"), parid = paridDom.val();
                    if (!paridDom.prop("checked")) {
                        var parid_treeid = $tree.tree('getNodeById', parid)
                        if (parid_treeid) {
                            $tree.tree('openNode', parid_treeid);
                        }
                    }
                }
            }
        }

        function setState(t) {

            var flag = $(t).prop("checked");
            var nodeid = $(t).val();
            if (flag) {
                setChildrenSelected(nodeid);
            }
            else {
                var node = $tree.tree('getNodeById', nodeid);
                if (node.children.length > 0) {
                    $(node.element).find("input[type=checkbox]").prop("checked", false);
                }
            }
        }
    </script>
}